import commonEventManager from '@ohos.commonEventManager'
import { BusinessError } from '@kit.BasicServicesKit';
import { JSON } from '@kit.ArkTS';


// Publisher通讯事件类型
enum PublishEventType {
  APP_PUBLISH = "APP_PUBLISH",
  CARD_PUBLISH = "CARD_PUBLISH"
}


class IPCManagerClass {
  static publishCount:number = 1
  // 发布者
  static publish(eventType:PublishEventType,data:string){
    // commonEventManager作用：可用于进程间通讯
    commonEventManager.publish(eventType,{data},(err)=>{
      if(err){
        console.log('result-->',`IPCManagerClass,publish formId:${data} Failed.Err:`+JSON.stringify(err))
        // 失败只发3次
        if(IPCManagerClass.publishCount<3){
          IPCManagerClass.publishCount ++;
          IPCManagerClass.publish(eventType,data);
        }
      }else{
        IPCManagerClass.publishCount = 1
        console.log('result-->',`IPCManagerClass,publish formId:${data} Successed.`)
      }
    })
  }
  // 订阅者
  static subscribe(eventType:PublishEventType,subscriber?:commonEventManager.CommonEventSubscriber,callback?:(event:string)=>void){
    commonEventManager.createSubscriber({ events: [eventType] }, (err, data) => {
      if (err) {
        return console.log('result-->', `IPCManagerClass,subscribe,创建订阅者error ${JSON.stringify(err)}`)
      }
      console.log('result-->', `IPCManagerClass,subscribe,创建订阅者success`)
      subscriber = data
      if (subscriber !== null) {
        //订阅事件
        commonEventManager.subscribe(subscriber, (err:BusinessError, data:commonEventManager.CommonEventData) => {
          if (err) {
            return console.error(`result-->`, 'IPCManagerClass,subscribe,订阅事件失败')
          }
          console.log('result-->',`IPCManagerClass,subscribe,接收订阅：收到发布者传送过来数据，formId:${data.data}`)
          callback!(data.data!)
        })
      } else {
        console.error('result-->',`IPCManagerClass,subscribe,需要创建subscriber`);
      }
    })
  }
}

export {IPCManagerClass,PublishEventType}